package com.db.compare.interceptor;

import com.db.compare.model.RbacUser;
import com.db.compare.service.RbacUserService;
import com.db.compare.utils.SecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String username =SecurityUtils.getUsername();
        HttpSession session=request.getSession();
        if(StringUtils.isNotBlank(username)){
            RbacUser user = (RbacUser) session.getAttribute("user");
            if(user!=null && username.equals(user.getMobile())){
                return true;
            }
        }
        /**
         * boolean 值： 确定了拦截器其余两方法是否执行
         */
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        System.out.println("TimeInterceptor 运行 Controller 某个方法时，方法抛出异常将不进入此方法");

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        System.out.println("TimeInterceptor 完成 Controller 某个方法");

    }

}
